<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
if (!function_exists('build_ranstr')) {
    /**
     * 获得随机字符串
     * @param   Number  $len    需要的长度
     * @param   Bool    $special    是否需要特殊符号
     * @return  String  返回随机字符串
     */
    function build_ranstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

if (!function_exists('upload')) {
    /**
     * @param String $name 图片字段名
     * @return 返回结果
     */
    function upload($name, $path = 'uploads')
    {
        // 获取到上传内容 => $_FILES
        $file = request()->file($name);
        // return $file;
        if ($file) {
            $path = ROOT_PATH . '/public/' . $path;

            $info = $file->move($path);

            if ($info) {
                $filename = $info->getSaveName();

                $filename = str_replace('\\', '/', '/uploads/' . $filename);


                return ['msg' => '上传成功', 'code' => 1, 'data' => $filename];
            } else {
                return ['msg' => $file->getError(), 'code' => 0, 'data' => null];
            }
        }

        return false;
    }
}

// 评论数据
if (!function_exists('CommentTree')) {
    //创建一个公共函数，来处理评论的递归  处理数据
    /**
     * @param list 评论数据
     * @param pid 评论上一级id
     * @param User 用户
     */
    function CommentTree($list, $pid = 0, $User)
    {
        // 定义空的数组
        $data = [];

        if ($list) {
            // 循环评论数据
            foreach ($list as $item) {
                // 评论里的点赞字段不为空
                if (!empty($item['like'])) {
                    //字符串转数组
                    $LikeArr = explode(',', $item['like']);
                    $LikeArr = array_filter($LikeArr);  //去除数组中的空元素
                    // 获取点赞的总数
                    $LikeCount = is_array($LikeArr) ? count($LikeArr) : 0;

                    // 自定义一个数据表不存在的字段
                    $item['like_count'] = $LikeCount;

                    //判断当前这一条评论是不是本人点过赞
                    // $user['id']
                    // $LikeArr
                    // echo $User['id'];
                    // halt($LikeArr);
                    if (in_array($User['id'], $LikeArr)) {
                        // 点过赞
                        // echo 111;
                        // exit;
                        $item['active'] = true;
                    } else {
                        // echo 11;
                        // exit;
                        $item['active'] = false;
                    }
                } else {
                    //当like字段为空
                    $item['like_count'] = 0;
                }



                //id = 1 pid = 0
                if ($item['pid'] == $pid) {
                    //找出相等pid值，给当前的评论新增一个自定义属性
                    //递归找子集
                    $item['child'] = CommentTree($list, $item['id'], $User);
                    $data[] = $item;
                }
            }
        }

        return $data;
    }
}

// 评论输出
if (!function_exists('CommentHtml')) {
    //处理递归循环输出  处理输出
    /**
     * @param list 评论数据
     * @param post 当前帖子数据
     * @param flag 是否为父级评论
     * @return output 返回递归数据
     */
    function CommentHtml($list, $post, $LoginUser, $flag = 'top', $output = "")
    {
        // $output = "";

        foreach ($list as $key => $item) {
            // 外边距
            $PaddingLeft = $item['level'] * 1;

            $output .= "<li style='padding-left:{$PaddingLeft}em' class='jieda-daan'>";
            // 头像
            $output .= "<div class='detail-about detail-about-reply'>";
            // 头像
            $url = url('home/user/index', ['userid' => $item['userid']]);
            $output .= "<a class='fly-avatar' href='$url'>";

            //判断头像
            if (is_file('.' . $item['user']['avatar'])) {
                $avatar = $item['user']['avatar'];
                $output .= "<img src='$avatar' />";
            } else {
                $output .= "<img src='/static/home/res/images/avatar/default.png' />";
            }
            $output .= "</a>";


            // 用户信息
            $output .= "<div class='fly-detail-user'>";
            $output .= "<a href='javascript:void(0)' class='fly-link'>";
            $nickname = $item['user']['nickname'];
            $output .= " <cite>$nickname</cite>";

            if ($item['user']['auth'] > 0) {
                $output .= "<i class='iconfont icon-renzheng'></i>";
            }
            $output .= "</a>";

            // 楼主
            if ($flag == 'top') {
                $output .= "<span style='color:#FF7200'>(楼主)</span>";
            }

            // 判断是否为发帖人
            if ($item['userid'] == $post['userid']) {
                $output .= "<span style='color:#5FB878'>(发帖人)</span>";
            }
            $output .= "</div>";

            // 评论时间
            $output .= "<div class='detail-hits'>";
            $output .= "<span>{$item['createtime']}</span>";
            $output .= "</div>";


            // 采纳图标
            if ($item['accept'] == 1) {
                $output .= "<i class='iconfont icon-caina' title='最佳答案'></i>";
            }
            $output .= "</div>";

            // 评论内容
            $output .= "<div class='detail-body jieda-body photos'>";
            $output .= "<p>{$item['content']}</p>";
            $output .= "</div>";

            // 回复
            if (cookie('LoginUser')) {
                $output .= "<div class='jieda-reply'>";
                // 点赞
                if (!empty($item['active'])) {
                    $output .= "<span class='jieda-zan zanok' data-id='{$item['id']}' type='zan'>";
                } else {
                    $output .= "<span class='jieda-zan' data-id='{$item['id']}' type='zan'>";
                }
                $output .= "<i class='iconfont icon-zan'></i>";
                $output .= "<em>{$item['like_count']}</em>";
                $output .= "</span>";

                // 回复
                if (!$post['accept']) {
                    $pid = $item['id'];
                    $nickname2 = $item['user']['nickname'];
                    $output .= "<a href='#comment' class='reply' type='reply' data-pid='$pid' data-nickname='$nickname2'>";
                    $output .= "<i class='iconfont icon-svgmoban53'></i>\r\n回复";
                    $output .= "</a>";
                }
                $output .= "<div class='jieda-admin'>";
                // (登录的人 == 发帖userid)发帖人  || 评论本人（评论人 == 登录的人）

                $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

                if ($userid == $post['userid'] || $userid == $item['userid']) {
                    if (!$post['accept']) {
                        $output .= " <span type='del' class='del-com' data-id='{$item['id']}'>删除</span>";
                    }
                }

                // 登录用户 == 发帖人 => 给采纳图标
                if ($userid == $post['userid'] && $item['userid'] != $userid) {
                    if (!$post['accept']) {
                        $output .= "<span class='accept' data-comid='{$item['id']}' class='jieda-accept' type='accept'>";
                        $output .= "采纳";
                        $output .= "</span>";
                    }
                }
                $output .= "</div>";


                $output .= "</div>";
            }
            $output .= "</li>";

            //判断是否有子集
            if (!empty($item['child'])) {
                $output = CommentHtml($item['child'], $post, $LoginUser, 'son', $output);
            }
        }

        return $output;
    }
}

// 删除评论
if (!function_exists('DelComment')) {
    function DelComent($id)
    {
        $result = model('Post.Comment')->where('pid', $id)->select();
        if ($result == null) {
            model('Post.Comment')->destroy($id);
            return 1;
        } else {
            model('Post.Comment')->destroy($id);
            $child = model('Post.Comment')->where('pid', $id)->select();
            foreach ($child as $key => $item) {
                DelComent($item['id']);
            }
            return 1;
        }
    }
}

// 生成订单号
if (!function_exists('build_code')) {
    /**
     * 生成唯一订单号
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}
